package com.wtwd.campus.service.impl;

import com.wtwd.campus.dao.WXUserStudentPermissionMapper;
import com.wtwd.campus.service.StudentService;
import com.wtwd.campus.service.WXUserStudentPermissionService;
import com.wtwd.campus.wx.entity.WxUserStudentPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mjy
 * @date 2021/07/06
 * @description
 */
@Service
public class WXUserStudentPermissionServiceImpl implements WXUserStudentPermissionService {

    @Autowired
    private WXUserStudentPermissionMapper wxUserStudentPermissionMapper;

    @Autowired
    private StudentService studentService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer unbindWxUserByStudentIdAndWxUserId(Integer studentId, Integer wxUserId) {
        Integer rest = wxUserStudentPermissionMapper.unbindWxUserByStudentIdAndWxUserId(studentId, wxUserId);
        //查询该学生是否还存在绑定的微信用户
        List<Map<String, Object>> wxUserList = studentService.getWxUserByStudentId(studentId);
        if (wxUserList == null || wxUserList.size() == 0) {//如果没有微信用户绑定该学生了，将微信绑定状态改为未绑定
            studentService.updateStudentWxUserBindStatus(0, studentId);
        }
        return rest;
    }

    @Override
    public boolean authUnbindStudent(Integer userId, Integer studentId, Integer wxUserId) {
        if (userId.equals(wxUserId)) {
            return false;
        }
        List<WxUserStudentPermission> permissions = studentService.getWxUserStudentPermissionByStudentId(studentId);
        if (permissions != null && permissions.size() > 0) {
            List<WxUserStudentPermission> managerUser = permissions.stream().filter(
                    e -> userId.equals(e.getWxUser()) && MANAGER.equals(e.getIsManager())).collect(Collectors.toList()
            );
            if (managerUser != null && managerUser.size() > 0) {
                return true;
            }
        }
        return false;
    }
}
